<?php

namespace App\Http\Controllers;

use App\Article;
use App\Services\EsService;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function test()
    {
        dd(app('es'));
    }

    //  获取es索引结构
    public function getEsIndexstruct()
    {
        $struct = app('es')->indices()->getMapping(['index' => "article_index"]);
        dd($struct);
    }



    /**
     * 创建索引
     */
    public function createIndex()
    {
        $result = ((new EsService)->createIndex());

        dd($result);

//        array:3 [▼
//          "acknowledged" => true
//          "shards_acknowledged" => true
//          "index" => "article_index"
//        ]
    }

    /**
     * 删除索引
     */
    public function deleteIndex()
    {
        $result = ((new EsService)->deleteIndex());




        dd($result);

//        array:1 [▼
//          "acknowledged" => true
//        ]
    }

    /**
     * 添加数据
     */
    public function run()
    {
        $ids = [7];

        $data = Article::whereIn('id',$ids)->get();

        $result = (new EsService)->add($data,['author','title','body','countries','desc','created_at']);

        dd($result);

//        array:3 [▼
//          "took" => 15
//          "errors" => false
//          "items" => array:3 [▼
//            0 => array:1 [▼
//              "index" => array:9 [▼
//                "_index" => "article_index"
//                "_type" => "article_type"
//                "_id" => "8yik83EBzOhuf1N0cyBT"
//                "_version" => 1
//                "result" => "created"
//                "_shards" => array:3 [▼
//                  "total" => 3
//                  "successful" => 1
//                  "failed" => 0
//                ]
//                "_seq_no" => 0
//                "_primary_term" => 1
//                "status" => 201
//              ]
//            ]
//            1 => array:1 [▼
//              "index" => array:9 [▶]
//            ]
//            2 => array:1 [▶]
//          ]
//        ]
    }

    /**
     * 搜索
     */
    public function search()
    {
        /*分页查询*/
        $type = 'page';

        $q = [
            'size'      =>  1,
            'from'      =>  1,  //  数据偏移
            "body" => [
                "query" => [
                    "match_all" => new \stdClass()
                ]
            ]
        ];

        $data = (new EsService)->search($type,$q);

        dd($data);
    }

}
